package com.hndfsj.framework.propertyeditor;

import java.beans.PropertyEditorSupport;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Stream;

import org.springframework.util.StringUtils;

public class DatePropertyEditor extends PropertyEditorSupport {
	private List<DateFormat> matchFormats;
	private DateFormat matchFormat;
	private final boolean allowEmpty;

	private final int exactDateLength;// 经常用不到，保留不用

	/**
	 * Create a new DatePropertyEditor instance, using the given DateFormat for
	 * parsing and rendering.
	 * <p>
	 * The "allowEmpty" parameter states if an empty String should be allowed for
	 * parsing, i.e. get interpreted as null value. Otherwise, an
	 * IllegalArgumentException gets thrown in that case.
	 * 
	 * @param dateFormat
	 *            DateFormat to use for parsing and rendering
	 * @param allowEmpty
	 *            if empty strings should be allowed
	 */
	public DatePropertyEditor(boolean allowEmpty, String... dateFormat) {
		this.allowEmpty = allowEmpty;
		this.exactDateLength = -1;
		initMatchDateFormats(dateFormat);
	}

	private void initMatchDateFormats(String[] dateFormats) {
		matchFormats=new ArrayList<DateFormat>();
		Stream.of(dateFormats).forEach(dateFormat->{
			matchFormats.add(new SimpleDateFormat(dateFormat));
		});
		
	}

	public DatePropertyEditor(String... dateFormat) {
		this(true, dateFormat);
	}

	/**
	 * Parse the Date from the given text, using the specified DateFormat.
	 */
	@Override
	public void setAsText(String text) throws IllegalArgumentException {
		if (this.allowEmpty && !StringUtils.hasText(text)) {
			// Treat empty String as null value.
			setValue(null);
		} else if (text != null && this.exactDateLength >= 0 && text.length() != this.exactDateLength) {
			throw new IllegalArgumentException(
					"Could not parse date: it is not exactly" + this.exactDateLength + "characters long");
		} else {
			try {
				setValue(match(text));
			} catch (ParseException ex) {
				throw new IllegalArgumentException("Could not parse date: " + ex.getMessage(), ex);
			}
		}
	}

	private Date match(String text) throws ParseException {
		for (DateFormat dateFormat : matchFormats) {
			try {
				Date result=dateFormat.parse(text);
				matchFormat=dateFormat;
				return result;
			} catch (ParseException e) {
			}
		}
		throw new ParseException(text, 1);
	}

	/**
	 * Format the Date as String, using the specified DateFormat.
	 */
	@Override
	public String getAsText() {
		Date value = (Date) getValue();
		return (value != null ? this.matchFormat.format(value) : "");
	}
}
